package com.bishe.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bishe.config.DataException;
import com.bishe.entity.Club;
import com.bishe.entity.User;
import com.bishe.mapper.ClubMapper;
import com.bishe.service.ClubService;
import com.bishe.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @description 针对表【club】的数据库操作Service实现
* @createDate 2024-03-07 14:46:10
*/
@Service
public class ClubServiceImpl extends ServiceImpl<ClubMapper, Club>
    implements ClubService {

    @Resource
    private UserService userService;

    @Override
    public void joinClub(Map<String,String> map) {
        if (CollUtil.isEmpty(map)){
            throw new DataException("传参格式错误");
        }
        String userId = map.get("userId");
        String clubId = map.get("clubId");

        // 判断用户是否已经加入该社团
        User user = userService.getById(userId);
        if (StrUtil.isEmpty(user.getClubId())){
            user.setClubId(clubId);
            userService.updateById(user);
            return;
        }
        List<String> clubIds = Arrays.stream(user.getClubId().split(",")).collect(Collectors.toList());
        if (clubIds.contains(clubId)){
            throw new DataException("已加入该社团");
        }

        clubIds.add(clubId);
        user.setClubId(String.join(",", clubIds));
        userService.updateById(user);
    }

    @Override
    public Map<String, Object> getPopNum(String id) {
        QueryWrapper<Club> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        Club club = this.getOne(queryWrapper);
        if (club == null){
            throw new DataException("社团不存在");
        }
        List<User> list = userService.list(Wrappers.lambdaQuery(User.class).eq(User::getId, club.getUid()));
        long man = list.stream().filter(user -> user.getSex().equals("男")).count();
        long woman = list.stream().filter(user -> user.getSex().equals("女")).count();
        Map<String, Object> map = new HashMap<>();
        map.put("clubName", club.getClubName());
        map.put("man", man);
        map.put("women", woman);
        map.put("popSize", list.size());
        map.put("clubIntro", club.getClubIntro());
        return map;
    }
}




